package edu.ccut.saturn.component.loader.node;

/**
 * 用于解析logic组件配置文件中“分支”结点的加载类。
 * <p>继承了<code>NodeInfoLoader</code>,并实现了<code>loadNode</code>方法。<p>
 * 
 * @author 温建
 * @version 1.0 2008.8.18
 * 
 * @see <code>SwitchNodeInfo</code>
 */
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.dom4j.Element;
import org.osgi.framework.Bundle;

import edu.ccut.saturn.component.INodeInfo;
import edu.ccut.saturn.component.SaturnComponentException;
import edu.ccut.saturn.component.impl.node.SwitchNodeInfo;

public class SwitchNodeInfoLoader extends NodeInfoLoader {

	public static final String KEY_NODETYPE_SWITCH = "switch";

	public static final String KEY_SWITCH_IF = "if";

	public static final String KEY_SWITCH_IF_EXPR = "expr";

	public static final String KEY_SWITCH_IF_THEN = "then";

	public static final String KEY_SWITCH_IF_ISDEFAULT = "isDefault";

	@SuppressWarnings("unchecked")
	public List<INodeInfo> loadNode(Element root, Bundle bundle)
			throws SaturnComponentException {

		List<Element> switchNodeElements = root.elements(KEY_NODETYPE_SWITCH);
		List<INodeInfo> switchNodeInfos = new ArrayList<INodeInfo>(
				switchNodeElements.size());

		for (Element switchNodeElement : switchNodeElements) {
			String id = switchNodeElement.attributeValue(KEY_NODE_ID).trim();
			String x = switchNodeElement.attributeValue(KEY_NODE_X).trim();
			String y = switchNodeElement.attributeValue(KEY_NODE_Y).trim();
			String name = switchNodeElement.elementTextTrim(KEY_NODE_NAME);
			String description = switchNodeElement
					.elementTextTrim(KEY_NODE_DESCRIPTION);

			List<Element> testElements = switchNodeElement
					.elements(KEY_SWITCH_IF);

			List<Map<String, Object>> branches = null;
			String defaultNode = null;

			if (testElements != null) {
				branches = new ArrayList<Map<String, Object>>(testElements
						.size());

				for (Element testElement : testElements) {
					Map<String, Object> branch = new HashMap<String, Object>();
					String isDefault = testElement
							.attributeValue(KEY_SWITCH_IF_ISDEFAULT);

					String expr = testElement
							.elementTextTrim(KEY_SWITCH_IF_EXPR);

					String then = testElement
							.attributeValue(KEY_SWITCH_IF_THEN).trim();

					branch.put("next", then);
					branch.put("expr", expr);
					branches.add(branch);

					if ("true".equals(isDefault)) {
						defaultNode = then;
					}
				}
			}
			SwitchNodeInfo switchNodeInfo = new SwitchNodeInfo(id, name,
					description, null, null, branches, defaultNode, x, y);

			switchNodeInfos.add(switchNodeInfo);
		}

		return switchNodeInfos;
	}
}
